package com.ming.closeto.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;

import com.ming.closeto.base.BasePageAdapter;

import java.util.ArrayList;
import java.util.List;



/**
 * 自动轮播
 */
public class AutoViewPager extends ViewPager {

    private static final int AUTO_WANT = 0X11;

    // 数据源
    private List<View> mList = new ArrayList<>();
    // 轮播开关
    private boolean isStartAuto = false;
    // 轮播间隔时长
    private int autoTime = 3000;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AUTO_WANT:
                    if (isStartAuto) {
                        int index = getCurrentItem();
                        // 如果当前item超过了最大的页数
                        if (index >= mList.size() - 1) {
                            setCurrentItem(0);
                        } else {
                            setCurrentItem(index + 1);
                        }
                        mHandler.sendEmptyMessageDelayed(AUTO_WANT, autoTime);
                    }
            }
        }
    };

    public AutoViewPager(@NonNull Context context) {
        super(context);
    }

    public AutoViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    // 设置轮播间隔时间
    public void setAutoTime(int autoTime) {
        this.autoTime = autoTime;
    }

    // 获取轮播间隔时间
    public int getAutoTime() {
        return autoTime;
    }

    // 启动轮播 设置是否自动开始
    public void setStartAuto(boolean startAuto) {
        isStartAuto = startAuto;
        if (startAuto) {
            mHandler.sendEmptyMessage(AUTO_WANT);
        } else {
            mHandler.removeMessages(AUTO_WANT);
        }
    }

    // 获取启动状态
    public boolean getStratAuto() {
        return isStartAuto;
    }

    // 获取当前轮播状态
    public boolean isStartAuto() {
        return isStartAuto;
    }

    // 设置view
    public void setView(View view) {
        mList.add(view);
        setAdapter(new BasePageAdapter(mList));

        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }
}
